package com.noodles.mall.filter;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        System.out.println("CustomUrlDecisionManager: decide 开始");
        System.out.println("authentication: "+authentication);
        System.out.println("object: "+object);
        System.out.println("configAttributes: "+configAttributes);
        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)) {
                System.out.println("CustomUrlDecisionManager: decide 结束1");
                return;
            }
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    System.out.println("CustomUrlDecisionManager: decide 结束2");
                    return;
                }
            }
        }
        System.out.println("CustomUrlDecisionManager: ");
        throw new AccessDeniedException("权限不足，请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        System.out.println("CustomUrlDecisionManager: ");
        System.out.println("attribute: "+attribute);
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        System.out.println("CustomUrlDecisionManager: ");
        System.out.println("clazz: "+clazz);
        return true;
    }
}

